package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.business.builder.ErrorTypeBuilder;
import com.ray.business.check.ErrorTypeCheck;
import com.ray.business.service.ProdErrorTypeService;
import com.ray.business.table.dto.ErrorTypeQueryDTO;
import com.ray.business.table.entity.ProdErrorType;
import com.ray.business.table.params.error.ErrorTypeCreateParams;
import com.ray.business.table.params.error.ErrorTypeEditParams;
import com.ray.business.table.params.error.ErrorTypeQueryParams;
import com.ray.business.table.vo.ErrorTypeVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 异常相关服务
 * @Class: ErrorTypeApi
 * @Package com.ray.base.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class ErrorApi {

    @Autowired
    private ProdErrorTypeService prodErrorTypeService;


    /**
     * 查询异常列表信息 分页  非删除的
     * @param queryParams
     * @return
     */
    public Result<IPage<ErrorTypeVO>> pageErrorTypes(CommonPage<ErrorTypeQueryParams,Page<ErrorTypeVO>> queryParams){
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<ErrorTypeQueryDTO,ProdErrorType> commonPageBuilder = new CommonPageBuilder<>(ErrorTypeQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdErrorType> page = prodErrorTypeService.page(commonPageBuilder.bulid(),loginUser);
        List<ProdErrorType> steps = page.getRecords();
        //结果对象
        IPage<ErrorTypeVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if(ObjectUtil.isNotNull(steps)){
            pageList.setRecords(steps.stream().map(sysErrorType -> {
                ErrorTypeVO stepVO = new ErrorTypeVO();
                BeanUtil.copyProperties(sysErrorType,stepVO);
                return  stepVO;
            }).collect(Collectors.toList()));
        }else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,pageList);
    }

    /**
     * 查询异常列表信息--启用的异常
     * @param queryParams
     * @return
     */
    public Result<List<ErrorTypeVO>> queryErrorTypes(ErrorTypeQueryParams queryParams){
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ErrorTypeQueryDTO queryDTO = new ErrorTypeQueryDTO();
        BeanUtil.copyProperties(queryParams,queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<ProdErrorType> steps = prodErrorTypeService.list(queryDTO,loginUser);
        //查询对象
        List<ErrorTypeVO> list = new ArrayList<>();
        if(ObjectUtil.isNotNull(steps)){
            list = steps.stream().map(sysErrorType -> {
                ErrorTypeVO stepVO = new ErrorTypeVO();
                BeanUtil.copyProperties(sysErrorType,stepVO);
                return  stepVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,list);
    }




    /**
     * 创建异常
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createErrorType(ErrorTypeCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdErrorType prodErrorType = prodErrorTypeService.queryErrorByErrorName(createParams.getErrorName(), loginUser);
        new ErrorTypeCheck(prodErrorType).checkErrprName(null,SysMsgCodeConstant.Error.ERR10000002);
        ErrorTypeBuilder stepBuilder = new ErrorTypeBuilder();
        stepBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存异常信息
        if(!prodErrorTypeService.save(stepBuilder.bulid())){
            log.info("保存异常接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
       return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 编辑异常
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editErrorType(ErrorTypeEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdErrorType prodErrorType = prodErrorTypeService.queryErrorByErrorName(editParams.getErrorName(), loginUser);
        new ErrorTypeCheck(prodErrorType).checkErrprName(editParams.getErrorCode(),SysMsgCodeConstant.Error.ERR10000002);
        ErrorTypeBuilder stepBuilder = new ErrorTypeBuilder();
        stepBuilder.append(editParams).appendEdit(loginUser);
        //编辑异常信息
        if(!prodErrorTypeService.edit(stepBuilder.bulid(),loginUser)){
            log.info("编辑异常接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }


    /**
     * 删除异常
     * @param errorCode 异常编码
     * @return Result
     */
    @Transactional
    public Result<String> deleteErrorType(String errorCode) {
        ValidateUtil.hasLength(errorCode,"参数[errorCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdErrorType sysErrorType = prodErrorTypeService.queryErrorByErrorCode(errorCode,loginUser);
        new ErrorTypeCheck(sysErrorType).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        ErrorTypeBuilder stepBuilder = new ErrorTypeBuilder();
        stepBuilder.appendCode(errorCode).appendEdit(loginUser).delete();
        //删除异常信息
        if(!prodErrorTypeService.edit(stepBuilder.bulid(),loginUser)){
            log.info("删除异常接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 开启异常
     * @param errorCode 异常编码
     * @return Result
     */
    @Transactional
    public Result<String> openErrorType(String errorCode) {
        ValidateUtil.hasLength(errorCode,"参数[errorCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdErrorType sysErrorType = prodErrorTypeService.queryErrorByErrorCode(errorCode,loginUser);
        new ErrorTypeCheck(sysErrorType).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        ErrorTypeBuilder stepBuilder = new ErrorTypeBuilder();
        stepBuilder.appendCode(errorCode).appendEdit(loginUser).open();
        //开启异常信息
        if(!prodErrorTypeService.edit(stepBuilder.bulid(),loginUser)){
            log.info("开启异常接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 开启异常
     * @param errorCode 异常编码
     * @return Result
     */
    @Transactional
    public Result<String> closeErrorType(String errorCode) {
        ValidateUtil.hasLength(errorCode,"参数[errorCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdErrorType sysErrorType = prodErrorTypeService.queryErrorByErrorCode(errorCode,loginUser);
        new ErrorTypeCheck(sysErrorType).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        ErrorTypeBuilder stepBuilder = new ErrorTypeBuilder();
        stepBuilder.appendCode(errorCode).appendEdit(loginUser).close();
        //关闭异常信息
        if(!prodErrorTypeService.edit(stepBuilder.bulid(),loginUser)){
            log.info("关闭异常接口异常,参数:{}", JSON.toJSONString(stepBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,stepBuilder.getCode());
    }

    /**
     * 异常详情
     * @param errorCode 异常编码
     * @return Result
     */
    public Result<ErrorTypeVO> viewErrorType(String errorCode) {
        ValidateUtil.hasLength(errorCode,"参数[errorCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        ProdErrorType sysErrorType = prodErrorTypeService.queryErrorByErrorCode(errorCode,loginUser);
        new ErrorTypeCheck(sysErrorType).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        ErrorTypeVO stepVO = new ErrorTypeVO();
        BeanUtil.copyProperties(sysErrorType,stepVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,stepVO);
    }

}
